﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using WinRTXamlToolkit.Interactivity;

namespace Wimm.UI.Behaviors
{
    public class TextBoxInputBehavior:Behavior<TextBox>
    {
        private String _lastText;

        public static readonly DependencyProperty AllowDecimalProperty = DependencyProperty.Register(
        "AllowDecimal",
        typeof(bool),
        typeof(TextBoxInputBehavior),
        new PropertyMetadata(false));

        /// 
        /// True to allow a decimal point.
        /// 
        public bool AllowDecimal
        {
            get
            {
                return (bool)base.GetValue(AllowDecimalProperty);
            }

            set
            {
                base.SetValue(AllowDecimalProperty, value);
            }
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            _lastText = this.AssociatedObject.Text;

            this.AssociatedObject.TextChanged += AssociatedObject_TextChanged;
            if (this.AssociatedObject.InputScope == null)
            {
                InputScope inputScope = new InputScope();
                inputScope.Names.Add(new InputScopeName(InputScopeNameValue.Number));
                this.AssociatedObject.InputScope = inputScope;
            }
        
        }

        protected override void OnDetaching()
        {
            this.AssociatedObject.TextChanged -= AssociatedObject_TextChanged;

            base.OnDetaching();
        }

        void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox tb = this.AssociatedObject;

            if (this.AllowDecimal)
            {
                double value;
                if (String.IsNullOrEmpty(tb.Text) || Double.TryParse(tb.Text, out value))
                {
                    _lastText = tb.Text;
                    return;
                }
            }
            else
            {
                long value;
                if (String.IsNullOrEmpty(tb.Text) || long.TryParse(tb.Text,out value))
                {
                    _lastText = tb.Text;
                    return;
                }
            }

            tb.Text = _lastText;
            tb.SelectionStart = tb.Text.Length;
        }
    }
}
